package com.cntaiping.workutil.config;

import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.Properties;

@Configuration
@ConditionalOnProperty("execution(com.cntaiping.workutil.**.service.impl.*Impl.*(..))") //在哪个目录生效
public class TransactionConfig implements EnvironmentAware {
    private Environment environment;

    @Autowired
    private TransactionInterceptor advice;

    @Autowired
    @Qualifier("transactionManager")
    private PlatformTransactionManager txManager;

    /**
     * 使用默认自动代理事务
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        return new DefaultAdvisorAutoProxyCreator();
    }

    /**
     * 事务切点配置
     */
    @Bean
    public AspectJExpressionPointcutAdvisor aspectJExpressionPointcutAdvisor(){
        AspectJExpressionPointcutAdvisor ajepa = new AspectJExpressionPointcutAdvisor();
        Properties properties = new Properties();
        properties.setProperty("add*","PROPAGATION_REQUIRED");
        properties.setProperty("save*","PROPAGATION_REQUIRED");
        properties.setProperty("delete","PROPAGATION_REQUIRED");
        properties.setProperty("update*","PROPAGATION_REQUIRED");
        properties.setProperty("list*","PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("find*","PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("page*","PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("*WithTxNever*","PROPAGATION_NEVER");//编程式事务命名方式
        advice.setTransactionAttributes(properties);
        advice.setTransactionManager(txManager);

        ajepa.setAdvice(advice);
        String txExpression = "execution(com.cntaiping.workutil.**.service.impl.*Impl.*(..))";

        ajepa.setExpression(txExpression);
        String property = environment.getProperty("");
        return ajepa;






    }


    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }




}
